

module Remote

  class ImportImages
    def initialize url
      @server = Server.new(url)
      @list = @server.ask('/export/images', :list)[0]['images']
    end

    def import_image
      image = next_image

      if image.save
        shift
      else
        raise "Hm hm hmmm, could not save image."
      end
    end

    def get_image id
      file = @server.ask_file('/export/images', :get, :id => id)
      image = ImageFileRecord.from_hash file.info['image']
      image.data = file.data
      [image, file.info['image']]
    end

    def next_image
      raise 'No more images to import.' unless id = @list[0]
      get_image(id)[0]
    end

    def shift
      @list = @list - [@list[0]]
    end
  end

=begin
@i = Remote::ImportImages.new('http://playnim.appspot.com/')

@r = CssManager.instance.to_hash
@r.each { |selector, attrs|
  attrs.each { |a, v|
    if m = (v || '').match(/([0-9]+)(\.jpg)/)
      p m[1];
      @r[selector][a] =
        v.gsub(m[1]+m[2], ImageFileRecord.get(m[1].to_i).file_name);
    end
  }
};
CssManager.instance.load_hash @r
CssManager.instance.save
=end

  class ExportImages < Controller
    def list
      ImageFileRecord.all(:original => nil).map(&:id)
    end

    def index e
    end

    def on_list e
      e.respond({:images => list})
    end

    def on_get e
      image = ImageFileRecord.get(e.data['id'])
      e.respond({
          :file => image.data,
          :image => image.to_hash,
          :headers => {
            'Content-Type' => 'image/png'
          }
        })
    end
  end


end